package ru.sis.shop.listener;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

/**
 * Application Lifecycle Listener implementation class HibernateLookUpListener.
 * 
 */
@WebListener
public final class HibernateLookUpListener implements ServletContextListener {
	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * javax.servlet.ServletContextListener#contextInitialized(javax.servlet
	 * .ServletContextEvent)
	 */
	@Override
	public void contextInitialized(final ServletContextEvent event) {
		@SuppressWarnings("deprecation")
		final SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
		event.getServletContext().setAttribute("sessionFactory", sessionFactory);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see javax.servlet.ServletContextListener#contextDestroyed(javax.servlet.
	 * ServletContextEvent)
	 */
	@Override
	public void contextDestroyed(final ServletContextEvent event) {
		final SessionFactory sessionFactory = (SessionFactory) event.getServletContext().getAttribute("sessionFactory");
		if (sessionFactory != null) {
			sessionFactory.close();
		}
	}
}
